﻿using Microsoft.Extensions.DependencyInjection;
using Modules.FaceScan;
using Modules.FaceScan.Entitys;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.FaceScan.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class FaceScanRecordRepository : Repository<FaceScanRecord, DefaultDbContext>
    {
        private readonly IApplicationContext applicationContext;
        public FaceScanRecordRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
            this.applicationContext = applicationContext;
        }

        public IPagedList<FaceScanRecord> GetRecords(FaceScanRecordQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("face_scan_record.id")
                .From("face_scan_record")
                .InnerJoin("person as p").On("p.card_number=face_scan_record.id_card");

            #region 主管单位数据权限

            if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
            {
                sql.InnerJoin("project_group_member as c").On("p.person_id=c.person_id");
                sql.InnerJoin("project as prj").On($"c.project_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
                if (deptUser.Level == AdministrativeLevel.City)
                    sql.Append($" and prj.city_code={deptUser.CityCode}");
                if (deptUser.Level == AdministrativeLevel.Area)
                    sql.Append($" and prj.area_code={deptUser.AreaCode}");
            }
            #endregion 主管单位数据权限
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(p.name Like @0 or face_scan_record.id_card like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.ReferType.HasValue)
                sql.Where("refer_type=@0", query.ReferType.Value);
            if (query.IsPassed.HasValue)
                sql.Where("is_passed=@0", query.IsPassed.Value);
            if (query.StartTime.HasValue)
                sql.Where("face_scan_record.create_time>=@0", query.StartTime.Value);
            if (query.EndTime.HasValue)
                sql.Where("face_scan_record.create_time<=@0", query.EndTime.Value);
            if (query.ProjectId.HasValue)
            {
                sql.InnerJoin("project_group_member ").On("p.person_id=project_group_member.person_id");
                sql.Where("project_group_member.project_id ", query.ProjectId);
            }
            sql.OrderBy("face_scan_record.create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }
    }
}